﻿using System;
using System.Windows.Data;
using System.Windows.Media;

namespace SBPweb.RIA.Client.Controls.Converters
{

    public class ColorConverter : IValueConverter
    {

        #region IValueConverter Members

        //[ValueConversion(typeof(SolidColorBrush), typeof(string))]
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Color color = GetColorByArgbAsString(value.ToString());
            return new SolidColorBrush(color);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            SolidColorBrush brush = value as SolidColorBrush;
            return GetArgbAsStringByColor(brush.Color);
        }

        #endregion

        #region Static methods

        public static Color GetColorByArgbAsString(string val)
        {
            if (!string.IsNullOrEmpty(val))
            {
                val = val.Replace("#", "");
            }
            else
            {
                val = "00000000";
            }

            byte a = System.Convert.ToByte("ff", 16);
            byte pos = 0;
            if (val.Length == 8)
            {
                a = System.Convert.ToByte(val.Substring(pos, 2), 16);
                pos = 2;
            }

            byte r = System.Convert.ToByte(val.Substring(pos, 2), 16);
            pos += 2;

            byte g = System.Convert.ToByte(val.Substring(pos, 2), 16);
            pos += 2;

            byte b = System.Convert.ToByte(val.Substring(pos, 2), 16);

            return Color.FromArgb(a, r, g, b);
        }

        public static string GetArgbAsStringByColor(Color color)
        {
            return color.ToString();
            //return "#" + color.A.ToString("") + color.R.ToString() + color.G.ToString() + color.B.ToString();
        }

        #endregion

    }

}